#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2015年3月20日

@author: chenyongbing
'''
import sys,os,re
#current_dir = os.path.dirname(__file__)
current_dir = os.path.split(os.path.realpath(__file__))[0]
import datetime
import calendar
class TimeMethod(object):
    '''
    classdocs
    '''


    def __init__(self):
        '''
        Constructor
        '''
    
    
    def get_weekday(self,day):
        weekdays = {0:'星期一',1:'星期二',2:'星期三',3:'星期四',4:'星期五',5:'星期六',6:'星期日'}
        weeknum = datetime.date(int(day[:4]),int(day[5:7]),int(day[8:10])).weekday()
        return weekdays[weeknum]
    
    def get_slist_between_st_et(self,st=None,et=None,timeType = 1):
        u'''获取2个时间间的所有日期
            timeType : 
                1 ----  day
                2 ----  week
                3 ----  month
                4 ---- quarter
        '''
        dlist = []
        count = 0
        if st==None and et==None:
            st = et = datetime.date.today().strftime('%Y-%m-%d')
        elif st==None and et!=None:
            st = et
        elif st!=None and et==None:
            et = st
        nday = (datetime.date(int(st[:4]),int(st[5:7]),int(st[8:]))+ datetime.timedelta(-1)).strftime('%Y-%m-%d')
        while nday < et:
            
            ndate = (datetime.date(int(st[:4]),int(st[5:7]),int(st[8:]))+ datetime.timedelta(count))
            count+=1
            nday = ndate.strftime('%Y-%m-%d')
            if timeType == 2 and int(ndate.weekday())!=0:continue
            if timeType == 3 and int(ndate.day)!=1:continue
            if timeType == 4 and int(ndate.day)!=1 and int(ndate.month) not in [1,4,7,10]:continue
            
            dlist.append(nday)
        return dlist
    
    def get_day_start_sec(self,day=None):
        if day==None:
            day = datetime.date.today().strftime('%Y-%m-%d')
        t = datetime.datetime(int(day[:4]),int(day[5:7]),int(day[8:10]),0,0,0).strftime('%s')
        return int(t)
    
    def get_day_end_sec(self,day=None):
        if day==None:
            day = datetime.date.today().strftime('%Y-%m-%d')
        t = datetime.datetime(int(day[:4]),int(day[5:7]),int(day[8:10]),23,59,59).strftime('%s')
        return int(t)
    
    def get_num_between_2_day(self,st=None,et=None):
        if st == None:
            st = datetime.date.today().strftime('%Y-%m-%d')
        if et == None:
            et = datetime.date.today().strftime('%Y-%m-%d')
        if st == et :return 0
        
        return (datetime.date(int(et[:4]),int(et[5:7]),int(et[8:10])) - datetime.date(int(st[:4]),int(st[5:7]),int(st[8:10]))).days
    
    
    def get_last_st_et(self,startTime = None , endTime = None):
        delta_day = self.get_num_between_2_day(st=startTime, et=endTime)
        last_et = (datetime.date(int(startTime[:4]),int(startTime[5:7]),int(startTime[8:10])) - datetime.timedelta(1)).strftime('%Y-%m-%d')
        last_st = (datetime.date(int(startTime[:4]),int(startTime[5:7]),int(startTime[8:10])) - datetime.timedelta(delta_day+1)).strftime('%Y-%m-%d')
        return last_st , last_et
    
    def get_last_st_et_by_timeType(self,startTime,timeType,range='all',type='last'):
        u'''通过time及timeType获取上一个周期的st et
            range:all 周期的 全部
            range:end 截止到 st
            range:start 从st到末尾
        '''
        if timeType == 'day' or timeType==1:
            st = startTime[:10]
            et = st
            last_st = last_et = (datetime.date(int(st[:4]),int(st[5:7]),int(st[8:10])) - datetime.timedelta(1)).strftime('%Y-%m-%d')
        elif timeType == 'week' or timeType ==2:
            wk = datetime.date(int(startTime[:4]),int(startTime[5:7]),int(startTime[8:10])).weekday()
            if range in ('all','end'):
                st = (datetime.date(int(startTime[:4]),int(startTime[5:7]),int(startTime[8:10])) - datetime.timedelta(wk)).strftime('%Y-%m-%d')
            elif range in ('start'):
                st = startTime
                
            if range in ('all','start'):
                et = (datetime.date(int(st[:4]),int(st[5:7]),int(st[8:10])) + datetime.timedelta(6)).strftime('%Y-%m-%d')
            elif range in ('end'):
                et = startTime
            last_st = (datetime.date(int(st[:4]),int(st[5:7]),int(st[8:10])) - datetime.timedelta(7)).strftime('%Y-%m-%d')
            last_et = (datetime.date(int(et[:4]),int(et[5:7]),int(et[8:10])) - datetime.timedelta(7)).strftime('%Y-%m-%d')
        elif timeType == 'month' or timeType==3:
            if range in ('all','end'):
                st = startTime[:7]+'-01'
            elif range in ('start'):
                st = startTime
            if range in ('all','start'):
                et = st[:7] + '-'+ str(calendar.monthrange(int(st[:4]), int(st[5:7]))[1])
            elif range in ('end'):
                et = startTime
            month_st =     startTime[:7]+'-01'
            
            last_month_et = (datetime.date(int(st[:4]),int(st[5:7]),int(st[8:10])) - datetime.timedelta(1)).strftime('%Y-%m-%d')
            last_month_et_day = last_month_et[8:10]
            startTime_day = startTime[8:10]
            if range in ('all','end'):
                if int(startTime_day)>int(last_month_et_day):
                    last_et = last_month_et
                else:
                    last_et = last_month_et[:7]+'-'+startTime_day
                last_st = last_et[:7]+'-01'
            elif range in ('start'):
                if int(startTime_day)>int(last_month_et_day):
                    print startTime_day,last_month_et_day
                    self.logger.error('day error')
                    sys.exit()
                else:
                    last_st = last_month_et[:7]+'-'+startTime_day
                    last_et = last_month_et
        elif timeType=='quarter' or timeType==4:
            month = str(int((int(startTime[5:7])-1)/3)*3+1)
            if len(month)==1:
                month = '0'+month
            st = startTime[:4] +'-'+ month + '-01'
            #print st
            et = (datetime.date(int(st[:4]),int(int(st[5:7])+3),1) - datetime.timedelta(1)).strftime('%Y-%m-%d')
            last_st = st
            last_et = et
        if type=='last':
            return last_st,last_et
        else:
            return st,et
    
    def get_st_et_by_timeType(self,startTime,timeType,range='all'):
        u'''通过time及timeType获取本周期的st et'''
        return self.get_last_st_et_by_timeType(startTime, timeType=timeType, range=range, type='now')
 
 
    def check_date_format(self,day,format='[\d]{4}-[\d]{2}-[\d]{2}'):
        if re.search('^%s$'%format,day):
            return True
        return False
    
    
    
 
myTimeMethod = TimeMethod()       
    
if __name__ == '__main__':
    pass